<template>
  <el-dialog
    :visible.sync="dialogVisible"
    width="70%"
    @close="dialogClose"
    class="dateDialog"
  >
    <template slot="title">
      <el-button-group style="vertical-align: bottom;">
        <el-button
          class="active"
          :type="dateActive === 0 ? 'primary' : ''"
          size="small"
          @click="getInfo(0)"
        >
          周报
        </el-button>
        <el-button
          :type="dateActive === 1 ? 'primary' : ''"
          size="small"
          @click="getInfo(1)"
        >
          月报
        </el-button>
      </el-button-group>
      <el-date-picker
        v-if="dateActive === 0"
        style="width: 260px; margin: 0 12px;"
        size="small"
        v-model="weekDates"
        type="week"
        :format="dateFormat"
        :picker-options="pickerMonOptions"
        @change="getInfo"
        placeholder="选择周"
      ></el-date-picker>
      <el-date-picker
        v-else-if="dateActive === 1"
        style="width: 130px; margin: 0 12px;"
        size="small"
        :picker-options="pickerMonOptions"
        v-model="monDates"
        @change="getInfo"
        type="month"
        placeholder="选择月"
      ></el-date-picker>
      <el-button type="small" v-if="dateActive === 0" @click="preWeek()">
        上一周
      </el-button>
      <el-button
        type="small"
        v-if="dateActive === 0"
        @click="nextWeek()"
        :disabled="weekNextDisabled"
      >
        下一周
      </el-button>
      <el-button type="small" v-if="dateActive === 1" @click="preMonth()">
        上一月
      </el-button>
      <el-button
        type="small"
        v-if="dateActive === 1"
        @click="nextMonth()"
        :disabled="monthNextDisabled"
      >
        下一月
      </el-button>
    </template>
    <div class="title">
      <span>组合信息</span>
      <span>
        <span v-if="dateActive === 0">（周收益率：</span>
        <span v-else-if="dateActive === 1">（月收益率：</span>
        <span
          style="margin-right: 10px;"
          :class="{
            positiveFc1: backTestIncom > 0,
            negativeFc: backTestIncom < 0,
          }"
        >
          {{ backTestIncom }}%
        </span>
        最大回撤：{{ backTestdDrawDown }}%）
      </span>
    </div>
    <el-table
      border
      :resizable="false"
      size="small"
      :data="compositionTableData"
      style="width: 100%;"
      header-row-class-name="bg-gray"
      :header-cell-class-name="headerClassName"
      :cell-style="{ 'font-size': '14px' }"
      :header-cell-style="{ 'font-size': '14px' }"
    >
      <el-table-column
        v-for="item in tableCompositionHeader"
        :label="item.label"
        :key="item.label"
        :prop="item.prop"
        :width="item.width"
        :min-width="item.minWidth"
        header-align="center"
        align="center"
      >
        <template slot="header">
          <span v-if="item.label !== '类目/日期'">
            {{ item.label }}
          </span>
          <div v-else class="line">
            <span style="float: left; margin-top: 15px; margin-left: 10px;">
              类目
            </span>
            <span style="float: right; margin: 5px 10px;">日期</span>
          </div>
        </template>
        <template slot-scope="scope">
          <span
            :class="{
              positiveFc1: +scope.row[item.prop] > 0,
              negativeFc: +scope.row[item.prop] < 0,
            }"
          >
            {{ tableItem(scope.row[item.prop]) }}
          </span>
        </template>
      </el-table-column>
    </el-table>
    <div class="title"><span>分类信息</span></div>
    <el-table
      border
      :resizable="false"
      size="small"
      :data="classifyTableData"
      style="width: 100%;"
      :header-cell-class-name="headerClassName"
    >
      <el-table-column
        v-for="item in tableClassifyHeader"
        :label="item.label"
        :key="item.label"
        :width="item.width"
        :min-width="item.minWidth"
        header-align="center"
      >
        <el-table-column
          :prop="ctime.prop"
          :label="ctime.label"
          :min-width="ctime.minWidth"
          :width="ctime.width"
          v-for="ctime in item.children"
          :key="ctime.label"
          header-align="center"
          align="center"
        >
          <template slot="header">
            <span v-if="ctime.label !== '分类名称/类目'">
              {{ ctime.label }}
            </span>
            <div v-else class="line">
              <span style="float: left; margin-top: 15px; margin-left: 10px;">
                分类名称
              </span>
              <span style="float: right; margin: 5px 10px;">类目</span>
            </div>
          </template>
          <template slot-scope="scope">
            <span
              :class="{
                positiveFc1: +scope.row[ctime.prop] > 0,
                negativeFc: +scope.row[ctime.prop] < 0,
              }"
            >
              {{ tableItem(scope.row[ctime.prop]) }}
            </span>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <div class="title"><span>策略信息</span></div>
    <el-table
      border
      :resizable="false"
      size="small"
      :data="strategyTableData"
      style="width: 100%;"
      :header-cell-class-name="headerClassName"
    >
      <el-table-column
        v-for="item in tableStrategyHeader"
        :label="item.label"
        :key="item.label"
        :width="item.width"
        :min-width="item.minWidth"
        header-align="center"
      >
        <el-table-column
          :prop="ctime.prop"
          :label="ctime.label"
          :min-width="ctime.minWidth"
          :width="ctime.width"
          v-for="ctime in item.children"
          :key="ctime.label"
          header-align="center"
          align="center"
        >
          <template slot="header">
            <span v-if="ctime.label !== '策略名称/类目'">
              {{ ctime.label }}
            </span>
            <div v-else class="line">
              <span style="float: left; margin-top: 15px; margin-left: 10px;">
                策略名称
              </span>
              <span style="float: right; margin: 5px 10px;">类目</span>
            </div>
          </template>
          <template slot-scope="scope">
            <span
              :class="{
                positiveFc1: +scope.row[ctime.prop] > 0,
                negativeFc: +scope.row[ctime.prop] < 0,
              }"
            >
              {{ tableItem(scope.row[ctime.prop]) }}
            </span>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <div class="monthBtn" v-if="dateActive === 1">
      <el-button
        size="small"
        v-for="(item,index) in weekArr"
        :key="item.name"
        @click="backWeek(item.weekDate)"
      >
        {{ `第${index+1}周明细` }}
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import moment from 'moment'
import { getCompositionWeeklyAndMonthlyReport } from '@/api/combManage'
import { debounce } from '@/utils/validate'
export default {
  data() {
    return {
      pickerMonOptions: {
        disabledDate: (time) => {
          return time.getTime() > new Date(this.netWorthEndTime).getTime()
        },
      },
      dateActive: 0,
      weekDates: '',
      starDate: '',
      endDate: '',
      monDates: '',
      tableCompositionHeader: [],
      tableClassifyHeader: [],
      tableStrategyHeader: [],
      compositionTableData: [],
      classifyTableData: [],
      strategyTableData: [],
      strategyDetail: [],
      weekArr: [],
      backTestdDrawDown: 0,
      backTestIncom: 0,
      dialogVisible: false,
      monthNextDisabled: true,
      weekNextDisabled: true,
    }
  },
  computed: {
    tableItem: function() {
      return function(data) {
        if (data || data === 0) {
          if (typeof data === 'string') {
            return data
          }
          return data.toFixed(2) + '%'
        } else {
          return '-'
        }
      }
    },
    dateFormat: function() {
      if (this.weekDates) {
        const starDate = moment(this.weekDates - 1000 * 60 * 60 * 24).format(
          'MM.DD',
        )
        const endDate = moment(
          this.weekDates.getTime() + 1000 * 60 * 60 * 24 * 5,
        ).format('MM.DD')
        const year = this.weekDates.getFullYear()
        const month = this.weekDates.getMonth() + 1
        const weekNum = Math.ceil(this.weekDates.getDate() / 7)
        const date = `${year}年${month}月第${weekNum}周(${starDate}~${endDate})`
        return date
      }
      return ''
    },
  },
  props: {
    weekMonDialogVisible: {
      type: Boolean,
    },
    id: {
      type: String | Number,
      default: '',
    },
    netWorthEndTime: {
      type: String | Number,
    },
  },
  watch: {
    weekDates: function(newVal, oldVal) {
      if (newVal) {
        this.starDate = moment(newVal - 1000 * 60 * 60 * 24).format(
          'YYYY-MM-DD',
        )

        if (
          newVal.getTime() >= this.getOneDay(this.netWorthEndTime).getTime()
        ) {
          this.weekNextDisabled = true
        } else {
          this.weekNextDisabled = false
        }
        this.endDate = moment(
          this.weekDates.getTime() + 1000 * 60 * 60 * 24 * 5,
        ).format('YYYY-MM-DD')
      }
    },
    monDates: function(newVal, oldVal) {
      const maxMonth = new Date(this.netWorthEndTime)
      const yyyy = maxMonth.getFullYear()
      const mm = maxMonth.getMonth() + 1
      if (newVal.getTime() >= new Date(yyyy + '-' + mm + '-1').getTime()) {
        this.monthNextDisabled = true
      } else {
        this.monthNextDisabled = false
      }
    },
    weekMonDialogVisible: function(newVal, oldVal) {
      if (newVal) {
        this.dialogVisible = newVal
        this.dateActive = 0
        // 初始化默认本周
        this.weekDates = this.getOneDay(this.netWorthEndTime)
        this.monDates = this.getOneMon(this.netWorthEndTime)
        this.$nextTick(() => {
          this.getInfo(0)
        })
      }
    },
  },
  methods: {
    getInfo(type) {
      this.dateActive = type === 0 || type === 1 ? type : this.dateActive
      const data = {
        compositionId: this.id,
        startTime: '2022-05-01',
        endTime: '2022-05-01',
      }
      if (this.dateActive === 0) {
        data.startTime = this.starDate
        data.endTime = this.endDate
      } else if (this.dateActive === 1) {
        data.startTime = moment(this.monDates).format('YYYY-MM-DD')
        data.endTime = ''
      }
      console.log(data)
      getCompositionWeeklyAndMonthlyReport(data).then((res) => {
        // 组合信息
        this.setCompositionTableData(res.body.compositionDetail[0])
        // 分类信息
        this.setClassifyTableData(res.body.classifyDetail)
        // 策略信息
        this.setStrategyDetailTableData(res.body.strategyDetail)

        // 月周数统计
        if (this.dateActive === 1) {
          this.weekArr = []
          res.body.compositionDetail[0].list.map((item, index) => {
            this.weekArr.push({
              weekDate: item.dateString,
            })
          })
          const year = this.monDates.getFullYear()
          const monthDay = this.weekArr[0].weekDate.split('-')[0]
          const weekDates = this.getOneDay(`${year}-${monthDay}`)
          if(weekDates.getMonth()+1 !== this.monDates.getMonth()+1) {
            this.weekArr.shift();
          }
        }
      })
    },
    headerClassName({ row, column, rowIndex, columnIndex }) {
      if (
        column.label === '分类名称/类目' ||
        column.label === '类目/日期' ||
        column.label === '策略名称/类目'
      ) {
        return 'slash'
      }
      return ''
    },
    dialogClose() {
      this.$emit('update:weekMonDialogVisible', false)
    },
    preWeek() {
      if (!this.weekDates) {
        return
      }
      this.weekDates = new Date(
        this.weekDates.getTime() - 1000 * 60 * 60 * 24 * 7,
      )
      this.$nextTick(() => {
        debounce(this.getInfo, 500)()
      })
    },
    nextWeek() {
      if (!this.weekDates) {
        return
      }
      this.weekDates = new Date(
        this.weekDates.getTime() + 1000 * 60 * 60 * 24 * 7,
      )
      this.$nextTick(() => {
        debounce(this.getInfo, 500)()
      })
    },
    preMonth() {
      this.monDates = this.monDates ? this.monDates : this.getOneMon()
      const mm =
        this.monDates.getMonth() + 1 === 1 ? '12' : this.monDates.getMonth()
      const yyyy =
        this.monDates.getMonth() + 1 === 1
          ? this.monDates.getFullYear() - 1
          : this.monDates.getFullYear()
      this.monDates = new Date(`${yyyy}-${mm}-1`)
      this.$nextTick(() => {
        debounce(this.getInfo, 500)()
      })
    },
    nextMonth() {
      this.monDates = this.monDates ? this.monDates : this.getOneMon()
      const mm =
        this.monDates.getMonth() + 1 === 12 ? '1' : this.monDates.getMonth() + 2
      const yyyy =
        this.monDates.getMonth() + 1 === 12
          ? this.monDates.getFullYear() + 1
          : this.monDates.getFullYear()
      this.monDates = new Date(`${yyyy}-${mm}-1`)
      this.$nextTick(() => {
        debounce(this.getInfo, 500)()
      })
    },
    setCompositionTableData(tableData) {
      this.backTestdDrawDown = tableData.backTestdDrawDown || 0
      this.backTestIncom = tableData.backTestIncom || 0
      this.compositionTableData = [
        { dataType: 'backTestIncomeRate', name: '回测收益率' },
        { dataType: 'firmOfferIncomeRate', name: '实盘收益率' },
        { dataType: 'indexIncomeRate', name: '指数收益率' },
        { dataType: 'backTestFirmOfferExcess', name: '回测实盘超额' },
        { dataType: 'backTestIndexExcess', name: '回测指数超额' },
      ]
      this.tableCompositionHeader = [
        { label: '类目/日期', prop: 'name', width: 300 },
      ]
      tableData.list.map((item) => {
        this.tableCompositionHeader.push({
          label: item.dateString,
          prop: item.dateString,
          minWidth: 160,
        })
        this.compositionTableData.map((citem) => {
          if (item.compositionReportVo) {
            citem[item.dateString] = item.compositionReportVo[citem.dataType]
          } else {
            citem[item.dateString] = ''
          }
        })
      })
    },

    setClassifyTableData(tableData) {
      this.tableClassifyHeader = [
        {
          label: '日期',
          prop: '',
          width: 300,
          children: [{ label: '分类名称/类目', prop: 'name', width: 300 }],
        },
      ]
      this.classifyTableData = []
      tableData.map((item) => {
        const listTable = {
          name: item.strategyName,
          backTestIncom: item.backTestIncom, //回测收益率
          firmOfferIncom: item.firmOfferIncom, //实盘收益率
          backTestdDrawDown: item.backTestdDrawDown, //最大回撤
          firmOfferDrawDown: item.firmOfferDrawDown, //最大实盘
        }
        if (item.list) {
          item.list.map((citem) => {
            for (const key in citem.compositionReportVo) {
              if (
                key === 'backTestIncomeRate' ||
                key === 'firmOfferIncomeRate'
              ) {
                listTable[citem.dateString + key] =
                  citem.compositionReportVo[key]
              }
            }
            listTable[citem.dateString] = citem.compositionReportVo
          })
          this.classifyTableData.push(listTable)
        }
      })
      if (tableData[0].list) {
        tableData[0].list.map((item) => {
          const listHeader = {
            label: item.dateString,
            prop: '',
            width: 120,
          }
          listHeader.children = []
          if (item.compositionReportVo) {
            for (const key in item.compositionReportVo) {
              switch (key) {
                case 'backTestIncomeRate':
                  listHeader.children.push({
                    label: '回测',
                    minWidth: 60,
                    prop: item.dateString + key,
                  })
                  break
                case 'firmOfferIncomeRate':
                  listHeader.children.push({
                    label: '实盘',
                    minWidth: 60,
                    prop: item.dateString + key,
                  })
                  break
                default:
                  break
              }
            }
          } else {
            listHeader.children.push({
              label: '实盘',
              minWidth: 60,
              prop: item.dateString + 'firmOfferIncomeRate',
            })
            listHeader.children.push({
              label: '回测',
              minWidth: 60,
              prop: item.dateString + 'backTestIncomeRate',
            })
          }
          this.tableClassifyHeader.push(listHeader)
        })
      }
      this.tableClassifyHeader.push({
        label: '周收益率',
        minWidth: 120,
        prop: '',
        children: [
          { label: '回测', minWidth: 60, prop: 'backTestIncom' },
          { label: '实盘', minWidth: 60, prop: 'firmOfferIncom' },
        ],
      })
      this.tableClassifyHeader.push({
        label: '最大回撤',
        minWidth: 120,
        prop: '',
        children: [
          { label: '回测', minWidth: 60, prop: 'backTestdDrawDown' },
          { label: '实盘', minWidth: 60, prop: 'firmOfferDrawDown' },
        ],
      })
    },
    setStrategyDetailTableData(tableData) {
      this.tableStrategyHeader = [
        {
          label: '日期',
          prop: '',
          width: 300,
          children: [{ label: '策略名称/类目', prop: 'name', width: 300 }],
        },
      ]
      this.strategyTableData = []
      tableData.map((item) => {
        const listTable = {
          name: item.strategyName,
          backTestIncom: item.backTestIncom, //回测收益率
          firmOfferIncom: item.firmOfferIncom, //实盘收益率
          backTestdDrawDown: item.backTestdDrawDown, //最大回撤
          firmOfferDrawDown: item.firmOfferDrawDown, //最大实盘
        }
        if (item.list) {
          item.list.map((citem) => {
            for (const key in citem.compositionReportVo) {
              if (
                key === 'backTestIncomeRate' ||
                key === 'firmOfferIncomeRate'
              ) {
                listTable[citem.dateString + key] =
                  citem.compositionReportVo[key]
              }
            }
            listTable[citem.dateString] = citem.compositionReportVo
          })
        }
        this.strategyTableData.push(listTable)
      })
      if (!tableData[0].list) {
        return
      }
      tableData[0].list.map((item) => {
        const listHeader = {
          label: item.dateString,
          prop: '',
          width: 120,
        }

        listHeader.children = []
        if (item.compositionReportVo) {
          for (const key in item.compositionReportVo) {
            switch (key) {
              case 'backTestIncomeRate':
                listHeader.children.push({
                  label: '回测',
                  minWidth: 60,
                  prop: item.dateString + key,
                })
                break
              case 'firmOfferIncomeRate':
                listHeader.children.push({
                  label: '实盘',
                  minWidth: 60,
                  prop: item.dateString + key,
                })
                break
              default:
                break
            }
          }
        } else {
          listHeader.children.push({
            label: '实盘',
            minWidth: 60,
            prop: item.dateString + 'firmOfferIncomeRate',
          })
          listHeader.children.push({
            label: '回测',
            minWidth: 60,
            prop: item.dateString + 'backTestIncomeRate',
          })
        }
        this.tableStrategyHeader.push(listHeader)
      })
      this.tableStrategyHeader.push({
        label: '周收益率',
        minWidth: 120,
        prop: '',
        children: [
          { label: '回测', minWidth: 60, prop: 'backTestIncom' },
          { label: '实盘', minWidth: 60, prop: 'firmOfferIncom' },
        ],
      })
      this.tableStrategyHeader.push({
        label: '最大回撤',
        minWidth: 120,
        prop: '',
        children: [
          { label: '回测', minWidth: 60, prop: 'backTestdDrawDown' },
          { label: '实盘', minWidth: 60, prop: 'firmOfferDrawDown' },
        ],
      })
    },
    // 返回周报
    backWeek(date) {
      const year = this.monDates.getFullYear()
      this.weekDates = this.getOneDay(`${year}-${date.split('-')[0]}`)
      this.$nextTick(() => {
        this.getInfo(0)
      })
    },
    getOneDay(date) {
      const nowTemp = date ? new Date(date) : new Date()
      const c_time = nowTemp.getTime()
      const c_day = nowTemp.getDay() || 7
      const m_time = c_time - (c_day - 1) * 24 * 60 * 60 * 1000
      return new Date(m_time)
    },
    getOneMon(date) {
      const nowTemp = date ? new Date(date) : new Date()
      const year = nowTemp.getFullYear()
      const month = nowTemp.getMonth() + 1
      return new Date(year + '-' + month + '-1')
    },
  },
}
</script>
<style lang="scss">
.el-table--small th.slash {
  padding: 0;
  .cell {
    position: relative;
    height: 39px;
    padding: 0;
  }
}

.el-table {
  th {
    background: #f5f7fa;
  }
}
.dateDialog {
  margin-bottom: 5px;
  .el-dialog__header {
    padding: 20px;
  }
  .el-dialog__body {
    padding: 10px 20px;
    border-top: 1px solid #f0f0f0;
  }
}
</style>
<style scoped lang="scss">
.title {
  color: #333;
  font-size: 14px;
  margin: 10px 0;
  font-weight: bold;
}
.monthBtn {
  margin: 20px 0;
}
.line:before {
  content: '';
  position: absolute;
  width: 1px;
  height: 330px;
  bottom: 0;
  right: 0;
  background-color: grey;
  display: block;
  -webkit-transform: rotate(-10deg);
  transform: rotate(-83deg);
  -webkit-transform-origin: bottom;
  transform-origin: bottom;
  background: #d8d9db;
}
</style>
